// ConnectTimerThread.java
import java.util.*;
import java.util.concurrent.*;

class ConnectTimerThread extends Thread {

	//Some fields to pass along to the senderthread
	 private static ArrayList clients = new ArrayList();  	    			//Keeps track of the client information.
    	 private static ArrayList clientInitPoints = new ArrayList();  		//Keeps track of the client initial points.
    	 private LinkedBlockingQueue packetQueue = new LinkedBlockingQueue(); 			//Queue for the packets.        
    	 private Hashtable clientList = new Hashtable();				//A list of clients


	/** Rate at which timer is checked */
	protected int m_rate = 100;
	
	/** Length of timeout */
	private int m_length;

	/** Time elapsed */
	private int m_elapsed;

	
	/**
	  * Creates a timer of a specified length
	  * @param	length	Length of time before timeout occurs
	  */
	public ConnectTimerThread (int length, ArrayList clients, LinkedBlockingQueue packetQueue, ArrayList clientInitPoints, Hashtable clientList)
	{
		// Assign to member variable
		m_length = length;

		// Set time elapsed
		m_elapsed = 0;

		this.clients = clients;
		this.packetQueue = packetQueue;
		this.clientInitPoints = clientInitPoints;
		this.clientList = clientList;
	}

	
	/** Resets the timer back to zero */
	public synchronized void reset()
	{
		m_elapsed = 0;
	}

	/** Performs timer specific code */
	public void run()
	{
		// Keep looping
		for (;;)
		{
			// Put the timer to sleep
			try
			{ 
				Thread.sleep(m_rate);
			}
			catch (InterruptedException ioe) 
			{
				continue;
			}

			// Use 'synchronized' to prevent conflicts
			synchronized ( this )
			{
				// Increment time remaining
				m_elapsed += m_rate;
				System.out.println("Time remaining to join is :" +  (m_length - m_elapsed));
				// Check to see if the time has been exceeded
				if (m_elapsed > m_length)
				{
					// Trigger a timeout
					timeout();
					break;
				}
			}

		}
	}

	// Override this to provide custom functionality
	public void timeout()
	{
		//Timer elapsed so now call the RegServerSenderThread to send messages to the clients.
		new RegServerSenderThread(this.clients, this.packetQueue, this.clientInitPoints, this.clientList).start();	
	}
}